package org.vacoor.xqq.reply.impl.result;

import com.fasterxml.jackson.databind.JsonNode;
import org.vacoor.xqq.core.bean.Buddy;
import org.vacoor.xqq.core.bean.ClientType;
import org.vacoor.xqq.core.bean.Discussion;
import org.vacoor.xqq.core.bean.Status;
import org.vacoor.xqq.reply.DiscuInfoResolver;
import org.vacoor.xqq.reply.impl.JsonResolver;

/**
 * {"retcode":0,"result":{"info":{"did":2403758450,"discu_owner":4161048199,"discu_name":"Vacoor\u3001HelloWorld\u3001\u6D4B\u8BD5","info_seq":0,"mem_list":[{"mem_uin":4161048199,"ruin":272451590},{"mem_uin":2214963100,"ruin":2214963100}]},"mem_status":[{"uin":4161048199,"status":"online","client_type":1},{"uin":2214963100,"status":"online","client_type":41}],"mem_info":[{"uin":4161048199,"nick":"Vacoor"},{"uin":3497026635,"nick":"HelloWorld"},{"uin":2214963100,"nick":"\u6D4B\u8BD5"}]}}
 */
public class SimpleDiscuInfoResolver extends JsonResolver<Discussion> implements DiscuInfoResolver {

    @Override
    protected Discussion doResolveResult(JsonNode result) {
        JsonNode info = result.get("info");
        long did = info.get("did").asLong();
        String name = info.get("discu_name").asText();
        int sort = info.get("info_seq").asInt(0);

        Discussion discu = createDiscussion(did, name);
        discu.setSort(sort);

        for (JsonNode mem : info.get("mem_list")) {
            long mem_uin = mem.get("mem_uin").asLong();
            long ruin = mem.get("ruin").asLong();
            Buddy buddy = createBuddy(mem_uin);
            buddy.setNo(ruin);
            discu.addMember(buddy);
        }

        // ---
        for (JsonNode mStatus : result.get("mem_status")) {
            long uin = mStatus.get("uin").asLong();
            Buddy buddy = discu.getMember(uin);
            if (buddy == null) {
                continue;
            }
            String statusStr = mStatus.get("status").asText();
            int clientCode = mStatus.get("client_type").asInt(0);
            Status st = Status.fromString(statusStr);
            ClientType clientType = ClientType.fromCode(clientCode);
            buddy.setStatus(st);
            buddy.setClientType(clientType);
        }

        for (JsonNode memInfo : result.get("mem_info")) {
            long mUin = memInfo.get("uin").asLong();
            String nick = memInfo.get("nick").asText();
            Buddy buddy = discu.getMember(mUin);
            if (buddy != null) {
                buddy.setNick(nick);
            }
        }
        return discu;
    }

    protected Discussion createDiscussion(long did, String name) {
        return new Discussion(did, name);
    }

    /**
     * 如果希望和好友列表关联可以重写改方法, 优先从好友列表查找
     */
    protected Buddy createBuddy(long uin) {
        return new Buddy(uin);
    }
}
